<?php

namespace App\Console\Commands;

use App\Plugins\Plugin;
use Illuminate\Console\Command;

class InstallPlugin extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'plugin:install 
                            {name : the name of plugin}
                            {--class= :the provider of plugin}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install a new plugin';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $class = $this->option('class');
        $pluginName = $this->argument('name');
        preg_match('/(?<=\\\)[a-zA-Z]+$/', $class, $match);
        if (!$match) {
            return $this->error('Class must contains namespace.');
        }
        $provider = $match[0];
        $namespace = substr($class, 0, -1 - strlen($provider));

        $plugin = new Plugin();
        if ($plugin->findByName($pluginName)) {
            return $this->error("Plugin [{$pluginName}] is already exist");
        }
        $plugin->install($pluginName, $namespace, $provider);
    }
}
